package com.ibeeking.found.msg.rest.utils;

import com.ibeeking.found.msg.service.common.po.SendEmailParamPO;
import com.ibeeking.found.msg.service.common.vo.EmailConfigVO;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Component;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 邮件工具类
 *
 * @Author ibeeking
 */
@Component
public class EmailUtil {

    /**
     * 发送邮件实现
     *
     * @param emailConfigVO
     * @param sendEmailParam
     * @throws GeneralSecurityException
     * @throws MessagingException
     */
    public static void sendEmail(EmailConfigVO emailConfigVO, SendEmailParamPO sendEmailParam) throws GeneralSecurityException, MessagingException {
        Properties properties = new Properties();
        // 指定连接的邮件服务器的主机名。如：qq邮箱就填写smtp.qq.com
        properties.put("mail.smtp.host", emailConfigVO.getSendHost());
        // 指定邮件发送协议：smtp。smtp：发邮件；pop3：收邮件
        properties.put("mail.transport.protocol", emailConfigVO.getSendProtocol());
        // 指定客户端是否要向邮件服务器提交验证
        properties.put("mail.smtp.auth", "true");
        // 邮箱需要设置SSL加密
        MailSSLSocketFactory factory = new MailSSLSocketFactory();
        factory.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", factory);

        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfigVO.getSenderEmail(), emailConfigVO.getSenderEmailPassword());
            }
        });

        // 当设置为true，JavaMail API就会将其运行过程和邮件服务器的交互命令信息输出到console中，用于JavaMail的调试
        session.setDebug(true);
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 设置邮件发送方
        message.setFrom(new InternetAddress(emailConfigVO.getSenderEmail()));
        // 设置邮件接收方
        for (String toItem : sendEmailParam.getTo()) {
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toItem));
        }
        // 设置邮件主题
        message.setSubject(sendEmailParam.getSubject());
        // 设置邮件内容
        if (StringUtils.isNotBlank(sendEmailParam.getContentType())) {
            message.setContent(sendEmailParam.getContent(), sendEmailParam.getContentType());
        } else {
            message.setContent(sendEmailParam.getContent(), "text/html;charset=UTF-8");
        }
        // 根据Session获取邮件传输对象
        Transport transport = session.getTransport();
        // 连接邮件服务器，前两个参数可以省略
        transport.connect(emailConfigVO.getSendHost(), emailConfigVO.getSendPort(), emailConfigVO.getSenderEmail(), emailConfigVO.getEmailConfigSsl().getSenderAuthCode());
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
